package com.wust.smartcity.common.interceptors.context;

import com.wust.smartcity.common.annotations.AppApi;
import com.wust.smartcity.common.annotations.FeignApi;
import com.wust.smartcity.common.annotations.OpenApi;
import com.wust.smartcity.common.annotations.WebApi;
import com.wust.smartcity.common.context.DefaultBusinessContext;
import com.wust.smartcity.common.enums.ApplicationEnum;
import com.wust.smartcity.common.exception.BusinessException;
import org.springframework.web.method.HandlerMethod;
import javax.servlet.http.HttpServletRequest;

/**
 * @author ：wust
 * @date ：Created in 2019/8/8 10:04
 * @description：
 * @version:
 */
public class StrategyContext {
    private StrategyContext(){}
    private static final StrategyContext instance = new StrategyContext();
    public static StrategyContext getInstance(){
        return instance;
    }

    public void setDefaultBusinessContext(HttpServletRequest request,HandlerMethod handlerMethod,String dataSourceGroup) {
        FeignApi feignApiAnnotation = handlerMethod.getBeanType().getAnnotation(FeignApi.class);
        OpenApi openApiAnnotation = handlerMethod.getBeanType().getAnnotation(OpenApi.class);
        AppApi appApiAnnotation = handlerMethod.getBeanType().getAnnotation(AppApi.class);
        WebApi webApiAnnotation = handlerMethod.getBeanType().getAnnotation(WebApi.class);

        String reqUrl = request.getRequestURI();

        if (reqUrl.contains("/login")
                || reqUrl.contains("/logout")
                || reqUrl.contains("/getAppLoginQRCode")) {
            DefaultBusinessContext.getContext().setDataSourceId(ApplicationEnum.DEFAULT.name());
        }else{
            if(feignApiAnnotation != null){ // 内部api请求
                IStrategy feignStrategy = new FeignStrategy();
                feignStrategy.setDefaultBusinessContext(request);
            }else if(openApiAnnotation != null){ // 开放api请求
                IStrategy openApiStrategy = new OpenApiStrategy();
                openApiStrategy.setDefaultBusinessContext(request);
            }else if(appApiAnnotation != null){
                IStrategy appStrategy = new AppApiStrategy();
                appStrategy.setDefaultBusinessContext(request);
            } else if(webApiAnnotation != null){// web前端请求
                IStrategy webStrategy = new WebStrategy();
                webStrategy.setDefaultBusinessContext(request);
            }else{ // 其他请求
                throw new BusinessException("非法的请求：无法识别的接口类型！");
            }
        }
    }
}
